package controllers

import (
	"bufio"
	"encoding/csv"
	"fmt"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"sync"
)

func splitCSVFile(inputFile string, outputPerFile int, saveFile string, wg *sync.WaitGroup) {
	wg.Done()
	// 打开输入 CSV 文件
	inFile, err := os.Open(inputFile)
	if err != nil {
		log.Fatal(err)
	}
	defer inFile.Close()

	reader := csv.NewReader(inFile)

	header, err := reader.Read()
	if err != nil {
		log.Fatal(err)
	}

	fileCount := 1
	recordCount := 0
	fileName := strings.Split(inputFile, ".")
	name := strings.Split(fileName[0], "\\")

	fmt.Println(fmt.Sprintf(saveFile+"/"+name[len(name)-1]+"_%d.csv", fileCount) + "开始写入")
	outFile, err := os.Create(fmt.Sprintf(saveFile+"\\"+name[len(name)-1]+"_%d.csv", fileCount))
	if err != nil {
		log.Fatal(err)
	}
	defer outFile.Close()
	writer := csv.NewWriter(outFile)
	writer.Write(header)
	fmt.Println(fmt.Sprintf(saveFile+"/"+name[len(name)-1]+"_%d.csv", fileCount) + "开始完成")
	for {
		record, err := reader.Read()
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Fatal(err)
		}
		writer.Write(record)
		recordCount++
		if recordCount == outputPerFile {
			writer.Flush()
			outFile.Close()
			fileCount++
			recordCount = 0
			outFile, err = os.Create(fmt.Sprintf(saveFile+"/"+name[len(name)-1]+"_%d.csv", fileCount))
			fmt.Println(fmt.Sprintf(saveFile+"\\"+name[len(name)-1]+"_%d.csv", fileCount) + "开始写入")
			if err != nil {
				log.Fatal(err)
			}
			defer outFile.Close()
			writer = csv.NewWriter(outFile)
			writer.Write(header)
			fmt.Println(fmt.Sprintf(saveFile+"\\"+name[len(name)-1]+"_%d.csv", fileCount) + "开始完成")
		}

	}
	writer.Flush()
}

// 分割 CSV 文件
// @router /split [get,post,put,delete]
func SplitterCSV() {
	file, err := os.Open("./config.txt")
	if err != nil {
		fmt.Println("Error opening file:", err)
		return
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	var wg sync.WaitGroup
	for scanner.Scan() {
		line := scanner.Text()
		lineS := strings.Split(line, ",")
		inputFile := lineS[0]
		saveFile := lineS[2]
		outputPerFile, _ := strconv.Atoi(lineS[1]) // 每 100 行一个文件
		wg.Add(1)
		splitCSVFile(inputFile, outputPerFile, saveFile, &wg)
	}
	wg.Wait()
	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading file:", err)
	} else {
		fmt.Println("分割完成")
	}
}
